package com.sample.plove.authener.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * PackageName:com.sample.plover.utils
 * Author:Administrator
 * Time:2:49
 * Date:2019/5/14
 * Describe:
 */
public class JsonUtil {

    private JsonUtil() {

    }

    private static final Gson gson = new GsonBuilder().serializeNulls().disableHtmlEscaping().create();

    public static String toJson(Object obj) {
        if (obj == null) {
            return "{}";
        }
        if (obj instanceof String && StringUtils.isEmpty(obj.toString())) {
            return "{}";
        }
        String json;

        try {
            json = gson.toJson(obj);
        } catch (JsonIOException e) {
            json = "{}";
        }
        return json;
    }

    public static <T> T fromJson(String json, Class<T> cls) {
        if (json == null) {
            return null;
        }
        return gson.fromJson(json, cls);
    }

    public static <T> List<T> toList(String json, Class<T> cls) {
        if (json == null) {
            return null;
        }
        return gson.fromJson(json, new TypeToken<List<T>>() {
        }.getType());
    }


    public static <T> Map<String, T> toMap(String json) {
        return gson.fromJson(json, new TypeToken<Map<String, T>>() {
        }.getType());
    }
}
